const DB = uniCloud.database();
const DBCmd = DB.command;
const $ = DB.command.aggregate;
let dbJQL = null
//当前登录用户id
let uid
const uniID = require('uni-id-common')
module.exports = {
	_before: async function () { // 通用预处理器
		//客户端信息
		const clientInfo = this.getClientInfo()
		//云服务信息
		const cloudInfo = this.getCloudInfo()
		//token信息
		const token = this.getUniIdToken()
		dbJQL = uniCloud.databaseForJQL({ // 获取JQL database引用，此处需要传入云对象的clientInfo
			clientInfo
		})
		if(token) {
			const tokenRes  = await uniID.createInstance({
				clientInfo
			}).checkToken(token)
			
			if(tokenRes.uid) {
				uid = tokenRes.uid
			}
		}
	},
	/**
	 * method1方法描述
	 * @param {string} param1 参数1描述
	 * @returns {object} 返回值描述
	 */
	
	async getIndexCustomer(params) {
		// 参数校验，如无参数则不需要
		if (!params) {
			return {
				errCode: 'PARAM_IS_NULL',
				errMsg: '参数不能为空'
			}
		}
		if (!uid) {
			return {
				status:true,
				msg:'查询成功',
				myCustomerRes:[] 
			}
		}
		let {page,limit,...where}=params
		let myLevelRes=await dbJQL.collection('mydb-permission').where({user_id:uid}).field('type').get()
	
		let myLevelUserRes=await dbJQL.collection('mydb-permission, uni-id-users').where({parent_id:uid}).field('type,user_id.nickname,parent_id.nickname').get()
		console.log('myLevelUserRes',myLevelUserRes)
	
		let myLevel=myLevelRes.data[0] ?  myLevelRes.data[0]['type'] : 1  // 业务员: 1,团队长:2,管理员: 3,超级管理员: 4
		let myLevelUsers=myLevelUserRes.data && myLevelUserRes.data.length ? myLevelUserRes.data.map((item)=>item.user_id) : []
		myLevelUsers=[...myLevelUsers,uid]
		switch (myLevel){
			case 1:
				where.associated_users=uid
				break;
			case 2:
				where.associated_users=DBCmd.in(myLevelUsers)
				break;
			case 3:
				where.is_public=true
				break;
			default:
				where.is_public=true
				break;
		}
		
		console.log('where',where)

		// 业务逻辑
		let res=await dbJQL.collection('mydb-customer').where({...where}).field('birthday,debt_info,name,type,source,phone,create_date,is_public,status').orderBy('create_time', 'desc')
					.skip((page - 1) * limit)
					.limit(limit)
					.get()
		let favorites=await dbJQL.collection('mydb-customer-favorite').where({user_id:uid}).field('customer_id').get()
		// 返回结果
		res.data.forEach((item)=>{
			item.creator='李**'
		})
		return {
			status:true,
			msg:'查询成功',
			favorites:favorites.data,
			data:res.data //请根据实际需要返回值
		}
	},
	async getCustomerDetail(_id){
		// 业务逻辑
		const res =await dbJQL.collection('mydb-customer,uni-id-users').where({_id}).field('associated_users{username,nickname},birthday,debt_info,name,type,source,phone,status,phone').get() 
		return {
			status:true,
			msg:'查询成功',
			data:res.data[0] //请根据实际需要返回值
		}
	},
	// 客户提交需求保存
	async saveCustomer(params){
		if (!params) {
			return {
				errCode: 'PARAM_IS_NULL',
				errMsg: '内容不能为空'
			}
		}
		let result=await dbJQL.collection('mydb-customer').add(params)
		return {
			status:true,
			msg:'保存成功',
			result 
		}
	},
	// 收藏客户
	async favoriteCustomer(params){
		if (!params) {
			return {
				errCode: 'PARAM_IS_NULL',
				errMsg: '客户不能为空'
			}
		}
		let result=await dbJQL.collection('mydb-customer-favorite').add({
			user_id:uid,
			customer_id:params._id
		})
		return {
			status:true,
			msg:'收藏成功',
			result 
		}
	},
	async getCenterCount(){
		return {
			status:true,
			msg:'获取成功',
			result:{
				userMenus:[
					[
						
						{
							"title": '签到打卡',
							"to": '/pages/punch/punch',
							"icon": "compose"
						},
						
						{
							"title":'我的收藏',
							"to": '/pages/ucenter/read-news-log/read-news-log',
							"icon": "flag"
						},
						{
							"title": '我的积分',
							"to": '',
							"event": 'getScore',
							"icon": "paperplane"
						}
						
					],
					[{
						"title": '留言反馈',
						"to": '/uni_modules/uni-feedback/pages/opendb-feedback/opendb-feedback',
						"icon": "help"
					}, {
						"title": '邀请客户',
						"to": '/pages/invite/invite',
						"icon": "personadd"
					}, {
						"title": '设置中心',
						"to": '/pages/ucenter/settings/settings',
						"icon": "gear"
					}]
				],
				gridCounts:[{
						"text": '客户',
						"icon": "chat",
						"count": 0,
					},
					{
						"text": '签单',
						"icon": "auth",
						"count": 0,
					},
					{
						"text": '跟进',
						"icon": "calendar",
						"count": 0,
					}
				],
				gridPlans:[{
						"text": '新客户',
						"count": 30,
					},
					{
						"text": '签单',
						"count": 10,
					},
					{
						"text": '回访',
						"count": 40,
					}]
				
			}
		}
	},
	async getOptions(){
		return {
			typeOptions: [
			  { text: '信贷', value: 'credit' },
			  { text: '抵押', value: 'mortgage' },
			  { text: '购房', value: 'house_purchase' }
			],
			statusOptions: [
			  { text: '潜在客户', value: 'potential' },
			  { text: '待跟进', value: 'to_follow' },
			  { text: '意向客户', value: 'intention' },
			  { text: '上门客户', value: 'visit' },
			  { text: '成交客户', value: 'deal' }
			],
			sourceOptions: [
			  { text: '网络获客', value: 'online' },
			  { text: '渠道介绍', value: 'channel' },
			  { text: '电话销售', value: 'tel_sales' },
			  { text: '微信营销', value: 'wechat' },
			  { text: '客户转介绍', value: 'referral' }
			],
			debtOptions: [
			  { text: '无负债', value: '无负债' },
			  { text: '小于10w', value: '小于10w' },
			  { text: '小于50w', value: '小于50w' },
			  { text: '小于100w', value: '小于100w' },
			  { text: '超过100w', value: '超过100w' }
			]
		}
	},
	async getHomeData(){
		return {
			serviceList: [
			  { name: '信用贷款', icon: 'zhifubao', path: '/pages/service/credit' },
			  { name: '房屋抵押', icon: 'home', path: '/pages/service/mortgage' },
			  { name: '购房服务', icon: 'bag', path: '/pages/service/house' },
			  { name: '贷款计算', icon: 'order', path: '/pages/tools/calculator' }
			],
			applyOptions: [
			  { name: '消费服务', icon: 'rmb', path: '/pages/apply/consumer' },
			  { name: '企业服务', icon: 'coupon', path: '/pages/apply/business' },
			  { name: '二手房服务', icon: 'home', path: '/pages/apply/house' }
			],
			productList: [
			  {
				title: '安心房贷',
				desc: '专为刚需购房者设计',
				rate: '4.5%起',
				tags: ['期限长', '利率低'],
				path: '/pages/product/detail?id=1'
			  },
			  {
				title: '创业贷',
				desc: '支持小微企业主',
				rate: '4.8%起',
				tags: ['放款快', '额度高'],
				path: '/pages/product/detail?id=2'
			  }
			],
			videoList:[]
		}
	}
	
}
